package com.ktjiaoyu.service.impl;

import com.ktjiaoyu.service.UploadService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

@Service("uploadService") // 给 bean 命名
public class UploadServiceImpl implements UploadService {
    /* 上传文件的保存目录 */
    public static final String UPLOAD_PATH = "/statics/upload/";
    @Autowired
    private HttpServletRequest request; // 注入 request 主要为了获取本地路径
    @Override
    public String uploadFile(MultipartFile uploadFile,
                             String... allowFileExtends) throws Exception {
        Set<String> include = new HashSet(Arrays.asList(allowFileExtends));
        // 获取保存路径
        String rootPath = request.getServletContext()
                .getRealPath(UPLOAD_PATH);
        // 如果文件非空说明上传了文件数据
        if(uploadFile!=null && !uploadFile.isEmpty()){
            String fileName = uploadFile.getOriginalFilename();
            // 获得上传文件的扩展名
            String extension = StringUtils.getFilenameExtension(fileName);
            // 如果不包含扩展名
            if (!include.contains(extension)) {
                throw new Exception("上传文件仅支持" + include + "扩展名！ ");
            }
            String uploadFileName = UUID.randomUUID() + "." + extension;
            File file = new File(rootPath, uploadFileName);
            // 父目录不存在是无法保存的
            if (!file.getParentFile().exists()) {
                // 创建父目录
                file.getParentFile().mkdirs();
            }
            // 将上传的文件保存到本地路径
            uploadFile.transferTo(file);
            // 返回文件路径
            return UPLOAD_PATH + uploadFileName;
        }
        return null;
    }
}
